package com.example.app;

import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.DownloadListener;
import android.webkit.WebView;

import com.getcapacitor.BridgeActivity;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends BridgeActivity {
  public PluginCallback wpsPluginCallback;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initializes the Bridge
    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      // Additional plugins you've installed go here
       add(WpsPlugin.class);
       add(OAuthPlugin.class);
       add(DownloadPlugin.class);
    }});

    // 动态注册WPS回调
    IntentFilter filter = new IntentFilter();
    filter.addAction("cn.wps.moffice.broadcast.AfterSaved");
    registerReceiver(new SaveReceiver(), filter);

    WebView webView = findViewById(com.getcapacitor.android.R.id.webview);

    webView.setDownloadListener(new DownloadListener() {
      @Override
      public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
        //处理下载事件
        downloadByBrowser(url);
      }
    });
  }

  /**
   * 用系统浏览器下载
   * @param url
   */
  private void downloadByBrowser(String url) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.addCategory(Intent.CATEGORY_BROWSABLE);
    intent.setData(Uri.parse(url));
    startActivity(intent);
  }
}
